package cn.xshi.common;

import cn.xshi.common.annotation.Auth;
import cn.xshi.common.base.BaseAction;
import cn.xshi.common.constant.SessionConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.xshi.common.base.BaseResult;
import cn.xshi.common.entity.LoginEntity;
import cn.xshi.common.util.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
 * @Desc 全局client端
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@Api(value = "客户端登录API|客户端主页API",description = "客户端登录API|客户端主页API")
@RequestMapping("/client")
@Slf4j
public class Client extends BaseAction {

	@Resource
	private RestTemplateUtil restTemplateUtil;

	/**
	 * 登录
	 * @param loginEntity
	 * @param request
	 * @return
	 */
	@PostMapping(value="/login")
	@ApiOperation(value="登录", notes="登录")
	@Auth(value = "/client/login",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	public BaseResult login(@RequestBody(required=true)LoginEntity loginEntity, HttpServletRequest request){
//        Map<String,String> map = new HashMap<>();
//        map.put(CacheConstant.JEHC_CLOUD_KEY,baseUtils.getJehcCloudKey());
//        map.put(CacheConstant.JEHC_CLOUD_SECURITY,baseUtils.getJehcCloudSecurity());
//        BaseResult result = super.post(restOauthURL() + "/login",BaseResult.class,loginEntity,super.setHeaders(request,map));
		BaseResult result = restTemplateUtil.post(restTemplateUtil.restOauthURL() + "/login",BaseResult.class,loginEntity,request);
		return result;
	}

	/**
	 * 注销
	 * @param request
	 */
	@Auth(value = "/client/loginOut",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@PostMapping(value="/loginOut")
	@ApiOperation(value="注销", notes="注销")
	public BaseResult loginOut(HttpServletRequest request){
		return restTemplateUtil.post(restTemplateUtil.restOauthURL() + "/loginOut",BaseResult.class,request);
	}

	/**
	 * 初始化主页面
	 * @param request
	 * @return
	 */
	@PostMapping(value="/init")
	@Auth(value = "/client/init",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	@ApiOperation(value="初始化主页面", notes="初始化主页面")
	public BaseResult init(HttpServletRequest request){
		BaseResult baseResult = restTemplateUtil.post(restTemplateUtil.restOauthURL() + "/init",BaseResult.class, request);
		return baseResult;
	}

	/**
	 * 解锁
	 * @param request
	 */
	@Auth(value = "/client/unlock",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	@PostMapping(value="/unlock")
	@ApiOperation(value="解锁", notes="解锁")
	public BaseResult unlock(HttpServletRequest request,@RequestBody(required=true)LoginEntity loginEntity){
		return restTemplateUtil.post(restTemplateUtil.restOauthURL() + "/unlock",BaseResult.class,loginEntity,request);
	}

	/**
	 * 创建SessionId
	 * @param request
	 */
	@Auth(value = "/client/JSessionId",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/JSessionId")
	@ApiOperation(value="创建SessionId", notes="创建SessionId")
	public BaseResult GenJSessionId(HttpServletRequest request){
		return restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/JSessionId",BaseResult.class,request);
	}

	private static final int WIDTH = 200;// 生成的图片的宽度

	private static final int HEIGHT = 30;// 生成的图片的高度

	/**
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@Auth(value = "/client/verify",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/verify")
	@ApiOperation(value="创建验证码", notes="创建验证码")
	public void verify(HttpServletRequest request,HttpServletResponse response){
		// 设置响应头通知浏览器以图片的形式打开
		response.setContentType("image/jpeg");// 等同于response.setHeader("Content-Type",
		// 设置响应头控制浏览器不要缓存
		response.setDateHeader("expries", -1);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");

		// 1.在内存中创建一张图片
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
		// 2.虚拟画笔得到图片
		Graphics g = image.getGraphics();
		// 3.设置图片的背影色
		setBackGround(g);
		// 4.设置图片的边框
		setBorder(g);
		// 5.在图片上画干扰线
//		drawRandomLine(g);
		// 6.写在图片上随机数
		String random = drawRandomNum((Graphics2D) g);// 生成数字和字母组合的验证码图片


//		HttpHeaders headers = new HttpHeaders();
//		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//		headers.setContentType(type);
//		headers.add("cookie", request.getHeader("cookie"));
//		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//		HttpEntity<String> formEntity = new HttpEntity<String>( random, headers);
//	    Object obj = restTemplate.postForObject(restSysURL() + "/verify", formEntity, String.class);

		String sessionId = request.getParameter("sessionId");
		restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/verify?random="+random,BaseResult.class, request,restTemplateUtil.setHeaders(request, SessionConstant.SESSIONID,sessionId));
//		BaseResult baseResult = super.get(restOauthURL() + "/verify?random="+random,BaseResult.class, request);
//		if(baseResult.getSuccess() && null != baseResult.getData()){
//			httpSessionUtils.setCookie(SessionConstant.SESSIONID, ""+baseResult.getData(), response);
//		}
		try {
			ImageIO.write(image, "jpg", response.getOutputStream());
			log.info("生成验证码结束");
		} catch (IOException e) {
			log.error("生成验证码出现异常");
		}
	}

	/**
	 * 设置图片的背景色
	 * @param g
	 */
	private void setBackGround(Graphics g) {
		// 设置颜色
		g.setColor(Color.WHITE);
		// 填充区域
		g.fillRect(0, 0, WIDTH, HEIGHT);
	}

	/**
	 * 设置图片的边框
	 * @param g
	 */
	private void setBorder(Graphics g) {
		// 设置边框颜色
		g.setColor(Color.WHITE);
		// 边框区域
		g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
	}

	/**
	 * 在图片上画随机线条
	 * @param g
	 */
	private void drawRandomLine(Graphics g) {
		// 设置颜色
//		g.setColor(Color.GREEN);
		Random r=new Random();
		// 设置线条个数并画线
		for (int i = 0; i < 10; i++) {
			int x1 = r.nextInt(WIDTH);
			int y1 = r.nextInt(HEIGHT);
			int x2 = r.nextInt(WIDTH);
			int y2 = r.nextInt(HEIGHT);
			g.drawLine(x1, y1, x2, y2);
			//设置干扰线颜色
			Color color = new Color(20 + r.nextInt(210), 20 + r.nextInt(210), 20 + r.nextInt(210));
			g.setColor(color);
		}

	}

	/**
	 * 画随机字符
	 * @param g
	 */
	private String drawRandomNum(Graphics2D g) {
		// 设置颜色
		g.setColor(Color.RED);
		// 设置字体
		g.setFont(new Font("宋体", Font.BOLD, 30));

		// 数字和字母的组合
//		String baseNumLetter = "Aa0Bb1CcDd3EeFf5Gg6HhJjKkLl7MmN9nOoPp8QqRrSs2TtUuVv4WwXxYyZz";
		String baseNumLetter = "0123456789";
		return createRandomChar(g, baseNumLetter);
	}

	/**
	 * 创建随机字符
	 * @param g
	 * @param baseChar
	 * @return 随机字符
	 */
	private String createRandomChar(Graphics2D g, String baseChar) {
		StringBuffer sb = new StringBuffer();
		Random r=new Random();
		int x = 5;
		String ch = "";
		// 控制字数
		for (int i = 0; i < 6; i++) {
			// 设置字体旋转角度
			int degree = r.nextInt() % 30;
			ch = baseChar.charAt(new Random().nextInt(baseChar.length())) + "";
			//设置随机数的颜色
			Color color = new Color(20 + r.nextInt(210), 20 + r.nextInt(210), 20 + r.nextInt(210));
			g.setColor(color);
			sb.append(ch);
			// 正向角度
			g.rotate(degree * Math.PI / 180, x, 30);
			g.drawString(ch, x, 20);
			// 反向角度
			g.rotate(-degree * Math.PI / 180, x, 30);
			x += 30;
		}
		return sb.toString();
	}
}
